package com.search;

import java.util.Set;
import java.util.TreeSet;

/**
 * @BelongsProject: DataStructures
 * @BelongsPackage: com.search
 * @Author: 江岸
 * @CreateTime: 2021-02-28 11:31
 * @Description: 插值查找算法
 */
public class InsertValueSearch {
    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 6, 7, 9, 10, 16, 23,23,23 ,39, 108, 567, 900, 4561};
        int i = binarySearch(arr, 3);
        Set<Integer> integers = allIndex(arr, i);
        System.out.println(integers);

    }

    public static int binarySearch(int[] arr,int target){
        int left=0;
        int right=arr.length-1;
        int mid;
        while (true){
            System.out.println("hello");
            //此处求mid与二分查找不同
            //mid = left+(right-left)*(keyValue-leftValue)/(rightValue-leftValue)
            mid = left + (right-left)*(target-arr[left])/(arr[right]-arr[left]);
            if (arr[mid]<target){
                left=mid+1;
            }else if(arr[mid]>target){
                right = mid-1;
            }else{
                return mid;
            }
            if (left>right){
                return -1;
            }
        }
    }

    public static Set<Integer> allIndex(int[] arr, int index){
        if (index==-1){
            return null;
        }
        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(index);
        int target = arr[index];
        int j=index-1;
        while(j>=0){
            if (arr[j]==target){
                treeSet.add(j);
                j--;
            }else {
                break;
            }
        }
        int i=index+1;
        while(i<arr.length){
            if (arr[i]==target){
                treeSet.add(i);
                i++;
            }else {
                break;
            }
        }
        return treeSet;
    }
}
